package uk.co.droidinactu.sony.prst1.home.view;

import java.util.ArrayList;
import java.util.List;

import uk.co.droidinactu.sony.prst1.home.EditPreferences;
import uk.co.droidinactu.sony.prst1.home.R;
import uk.co.droidinactu.sony.prst1.home.data.Book;
import uk.co.droidinactu.sony.prst1.home.data.SonyDataModel;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public final class BooksActivity extends AbstractListActivity implements OnItemClickListener, OnClickListener {

    public static final int[] bookColsMapTo = new int[] { R.id.book_grid_item_img, R.id.book_grid_item_title,
            R.id.book_grid_item_author };

    public static final int[] bookColsMapToFilename = new int[] { R.id.book_grid_item_img, R.id.book_grid_item_filename };

    public static final String[] bookColumns = new String[] { BaseColumns._ID, Book.COLUMN_NAME_TITLE,
            Book.COLUMN_NAME_AUTHOR };

    public static final String[] bookColumnsFilename = new String[] { BaseColumns._ID, Book.COLUMN_NAME_FILE_NAME };

    public static final String LOG_TAG = "BooksActivity";

    public static String SELECTED_COLLECTION_ID = "SELECTED_COLLECTION_ID";
    private GridView bkGridView;
    private ImageButton btnFilter;
    private ImageButton btnGridList;
    private ImageButton btnSearch;
    private ImageButton btnSortOrdr;
    private final List<String> clctnFilter = new ArrayList<String>();
    private long colctnId = -1;
    private String colctnName = "";
    private Cursor cursr = null;
    private SonyDataModel dataModel;
    private String filterChar = "";
    private LinearLayout indexBtns;

    private final String PREF_FILTER_PREFIX = "PREF_FILTER_";
    private final String PREF_SORT_BY = "PREF_SORT_BY";

    private BookSortBy sortBy = BookSortBy.TITLE;
    private TextView txtSortOrdr;
    private TextView txtViewTitle;

    private String[] getBookColumns() {
        String[] columns = null;
        columns = BooksActivity.bookColumns;
        if (this.sortBy == BookSortBy.FILENAME) {
            columns[1] = Book.COLUMN_NAME_FILE_NAME;
        } else {
            columns[1] = Book.COLUMN_NAME_TITLE;
        }
        return columns;
    }

    private int[] getBookColumnsMapTo() {
        int[] mapTo = null;
        mapTo = BooksActivity.bookColsMapTo;
        return mapTo;
    }

    @Override
    public void onClick(final View v) {

        if (v.getTag() == null) {
            final String btnPressed = ((Button) v).getText().toString();
            this.filterChar = btnPressed;
            this.updateBooksGrid();

        } else if (v.getTag().equals("book_grid_txt_books")) {
            this.filterChar = null;
            this.updateBooksGrid();

        } else if (v.getTag().equals("book_grid_btn_filter")) {
            this.showFilterDialog();

        } else if (v.getTag().equals("book_grid_btn_grid")) {
            this.showNotImplementedDialog();

        } else if (v.getTag().equals("book_grid_btn_sort")) {
            if (this.sortBy == BookSortBy.TITLE) {
                this.sortBy = BookSortBy.AUTHOR;
            } else if (this.sortBy == BookSortBy.AUTHOR) {
                this.sortBy = BookSortBy.FILENAME;
            } else {
                this.sortBy = BookSortBy.TITLE;
            }

        } else if (v.getTag().equals("book_grid_btn_search")) {
            // Toast.makeText(this, "Not Implemented Yet!", Toast.LENGTH_LONG);
            this.showNotImplementedDialog();

        }
        this.updateBooksGrid();
    }

    // private void showSearchDialog() {
    //
    // final CharSequence[] items = new CharSequence[3];
    // items[0] = this.getResources().getString(R.string.book_grid_sort_title);
    // items[1] = this.getResources().getString(R.string.book_grid_sort_author);
    // items[2] =
    // this.getResources().getString(R.string.book_grid_sort_collection);
    //
    // final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    // builder.setTitle(R.string.book_grid_sort_dialog_title);
    // builder.setPositiveButton(R.string.book_grid_sort_dialog_btn_ok, new
    // DialogInterface.OnClickListener() {
    // @Override
    // public void onClick(final DialogInterface dialog, final int which) {
    // BooksActivity.this.updateBooksGrid();
    // }
    // });
    // builder.setSingleChoiceItems(items, this.sortBy, new
    // DialogInterface.OnClickListener() {
    // @Override
    // public void onClick(final DialogInterface dialog, final int item) {
    // BooksActivity.this.sortBy = item;
    // }
    // });
    // builder.show();
    // }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.book_grid);

        final Intent intent = this.getIntent();
        final Bundle extras = intent.getExtras();
        if (extras != null) {
            this.colctnId = extras.getLong(BooksActivity.SELECTED_COLLECTION_ID);
        }

        this.txtViewTitle = (TextView) this.findViewById(R.id.book_grid_txt_books);
        this.txtViewTitle.setOnClickListener(this);

        this.txtSortOrdr = (TextView) this.findViewById(R.id.book_grid_txt_sort_order);
        this.indexBtns = (LinearLayout) this.findViewById(R.id.book_grid_btn_index);

        this.btnGridList = (ImageButton) this.findViewById(R.id.book_grid_btn_grid);
        this.btnGridList.setOnClickListener(this);

        this.btnSearch = (ImageButton) this.findViewById(R.id.book_grid_btn_search);
        this.btnSearch.setOnClickListener(this);

        this.btnSortOrdr = (ImageButton) this.findViewById(R.id.book_grid_btn_sort);
        this.btnSortOrdr.setOnClickListener(this);

        this.btnFilter = (ImageButton) this.findViewById(R.id.book_grid_btn_filter);
        this.btnFilter.setOnClickListener(this);

        this.indexBtns.removeAllViews();
        Button btn = new Button(this);
        btn.setOnClickListener(this);
        btn.setText("0");
        this.indexBtns.addView(btn);

        for (char ch = 'A'; ch <= 'Z'; ch++) {
            btn = new Button(this);
            btn.setOnClickListener(this);
            // btn.setId();
            btn.setText("" + ch);
            this.indexBtns.addView(btn);
        }

        this.bkGridView = (GridView) this.findViewById(R.id.book_grid_books);
        this.bkGridView.requestFocus();
        this.bkGridView.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
        this.dataModel.launchBook(this, id);
    }

    @Override
    protected void onPause() {
        super.onPause();
        final SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        final SharedPreferences.Editor ed = mPrefs.edit();
        ed.putInt(this.PREF_SORT_BY, this.sortBy.ordinal());
        for (int x = 0; x < this.clctnFilter.size(); x++) {
            ed.putString(this.PREF_FILTER_PREFIX + x, this.clctnFilter.get(x));
        }
        ed.commit();
    }

    @Override
    protected void onResume() {
        super.onResume();

        final SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        int x = 0;
        String filterStr = mPrefs.getString(this.PREF_FILTER_PREFIX + x, "");
        while (filterStr.length() > 0) {
            this.clctnFilter.add(filterStr);
            x++;
            filterStr = mPrefs.getString(this.PREF_FILTER_PREFIX + x, "");
        }

        final int tmpSortOrdr = mPrefs.getInt(this.PREF_SORT_BY, BookSortBy.TITLE.ordinal());
        if (tmpSortOrdr == BookSortBy.FILENAME.ordinal()) {
            this.sortBy = BookSortBy.FILENAME;
        } else if (tmpSortOrdr == BookSortBy.AUTHOR.ordinal()) {
            this.sortBy = BookSortBy.AUTHOR;
        } else {
            this.sortBy = BookSortBy.TITLE;
        }

        if (this.dataModel == null) {
            this.dataModel = new SonyDataModel(this);
        }
        if (this.colctnId > -1) {
            this.colctnName = this.dataModel.getCollection(this.colctnId).title;
        }
        this.updateBooksGrid();
    }

    private void showFilterDialog() {

        final List<String> clctnNames = this.dataModel.getCollectionNames();
        final int nbrClctns = clctnNames.size();
        final boolean[] states = new boolean[nbrClctns];
        final CharSequence[] items = new CharSequence[nbrClctns];
        for (int x = 0; x < nbrClctns; x++) {
            items[x] = clctnNames.get(x);
            if (this.clctnFilter.contains(clctnNames.get(x))) {
                states[x] = true;
            } else {
                states[x] = false;
            }
        }

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.book_grid_filter_dialog_title);
        builder.setPositiveButton(R.string.book_grid_sort_dialog_btn_ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, final int which) {
                // BooksActivity.this.updateBooksGrid();
                BooksActivity.this.showNotImplementedDialog();
            }
        });
        builder.setMultiChoiceItems(items, states, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(final DialogInterface dialogInterface, final int item, final boolean state) {
                if (state) {
                    BooksActivity.this.clctnFilter.add(items[item].toString());
                } else {
                    BooksActivity.this.clctnFilter.remove(items[item].toString());
                }
            }
        });
        builder.show();
    }

    private void updateBooksGrid() {
        try {
            String sortOrderLblText;
            switch (this.sortBy) {
            case FILENAME:
                sortOrderLblText = this.getResources().getString(R.string.book_grid_sorted_filename);
                break;
            case AUTHOR:
                sortOrderLblText = this.getResources().getString(R.string.book_grid_sorted_author);
                break;
            default:
                sortOrderLblText = this.getResources().getString(R.string.book_grid_sorted_title);
                break;
            }
            this.txtSortOrdr.setText(sortOrderLblText);

            if (this.cursr != null) {
                try {
                    this.cursr.close();
                } catch (final Exception e) {
                }
            }

            if (this.filterChar != null && this.filterChar.length() > 0) {
                this.cursr = this.dataModel.getBooks(this, this.filterChar, this.sortBy);
                this.txtViewTitle.setText(String.format(this.getResources()
                        .getString(R.string.book_grid_title_filtered), this.filterChar));

            } else if (this.colctnName.length() > 0) {
                this.cursr = this.dataModel.getBooksInCollection(this.colctnName, this.sortBy);
                this.txtViewTitle.setText(String.format(
                        this.getResources().getString(R.string.book_grid_title_collection), this.colctnName));

            } else {
                this.cursr = this.dataModel.getBooks(this, this.sortBy);
                this.txtViewTitle.setText(this.getResources().getString(R.string.book_grid_title));
            }
            if (this.cursr == null) {
                return;
            }
            this.startManagingCursor(this.cursr);
            SimpleCursorAdapter tmpAdaptor = null;

            if (EditPreferences.useFilenames(this)) {
                tmpAdaptor = new SimpleCursorAdapter(this, R.layout.book_grid_item_filename, this.cursr,
                        bookColumnsFilename, bookColsMapToFilename);
            } else {
                tmpAdaptor = new SimpleCursorAdapter(this, R.layout.book_grid_item, this.cursr, this.getBookColumns(),
                        this.getBookColumnsMapTo());
            }

            tmpAdaptor.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
                @Override
                public boolean setViewValue(final View view, final Cursor cursor, final int columnIndex) {
                    boolean retval = false;
                    final int idColIndex = cursor.getColumnIndexOrThrow(BaseColumns._ID);
                    final int filenameColIndex = cursor.getColumnIndexOrThrow(Book.COLUMN_NAME_FILE_NAME);
                    final int thumbColIndex = cursor.getColumnIndexOrThrow(Book.COLUMN_NAME_THUMBNAIL);

                    if (columnIndex == idColIndex) {
                        try {
                            final ImageView coverImg = (ImageView) view;
                            final String thumbnailFilename = cursor.getString(thumbColIndex);
                            final Bitmap bitmap = SonyDataModel.getBookCoverImg(BooksActivity.this, thumbnailFilename);
                            coverImg.setImageDrawable(new BitmapDrawable(bitmap));
                            retval = true;
                        } catch (final Exception e) {
                            Log.e(LOG_TAG, "exception populating list", e);
                        }
                        retval = true;
                    } else if (columnIndex == filenameColIndex && BooksActivity.this.sortBy == BookSortBy.FILENAME) {
                        String filename = cursor.getString(filenameColIndex);
                        final TextView filenameView = (TextView) view;
                        if (filename.endsWith(".epub") || filename.endsWith(".mobi")) {
                            filename = filename.substring(0, filename.length() - 5);
                        } else if (filename.endsWith(".pdf")) {
                            filename = filename.substring(0, filename.length() - 4);
                        }
                        filenameView.setText(filename);
                        retval = true;
                    }
                    return retval;
                }
            });
            this.bkGridView.setAdapter(tmpAdaptor);
            tmpAdaptor.notifyDataSetChanged();
        } catch (final Exception e) {
            Log.e(LOG_TAG, "exception populating list", e);
            Toast.makeText(this, "Exception Caught creating book grid", Toast.LENGTH_SHORT).show();
        }
    }
}
